/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ucjava.chat.socialnetworking.userinterface;

import com.ucjava.chat.commserve.rmi.common.User;
import com.ucjava.chat.socialnetworking.contacts.IContacts;
import com.ucjava.chat.socialnetworking.contacts.IMyFriends;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;

/**
 *
 * @author adunagan
 */
public class AllUsersUI extends javax.swing.JFrame {

    //private static final String HOST = "localhost";
    //private static final int PORT = 2013;
    private static Registry registry;
    ArrayList<User> allContacts = null;
    //create default list model for all users
    DefaultListModel allModel = new DefaultListModel();
    // create DefaultListModel for search results
    DefaultListModel resultsModel = new DefaultListModel();

    //work around class to get strings to display properly
    class DisplayableUser extends User {

        @Override
        public String toString() {
            return this.getUserName();
        }
    }

    /**
     * Creates new form AllUsersUI
     */
    public AllUsersUI() throws RemoteException, NotBoundException {
        initComponents();



        // Pull Contacts from server and save them in an ArrayList to be used on the client
        registry = LocateRegistry.getRegistry();
        IContacts contacts = (IContacts) registry.lookup("AllContacts");
        allContacts = contacts.getUserList();

        //import friends list from the server
        IMyFriends fr = (IMyFriends) registry.lookup("MF");
        final ArrayList<User> myFriends = fr.getMyFriendsList();

        //for each user in all users add them to all users model
        for (int i = 0; i < allContacts.size(); i++) {
            //get user from array list
            User user = allContacts.get(i);
            //work around for getting proper string to display
            User dispUser = new DisplayableUser();
            dispUser.setUserName(user.getUserName());
            //add user to default list model
            allModel.add(i, dispUser);
        }

        //add all users model to JList
        listAllUsers.setModel(allModel);

        //listener for double clicks on names in all users list
        listAllUsers.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                JList list = (JList) evt.getSource();
                if (evt.getClickCount() == 2) {

                    //here is where we want to add users to friends list if double clicked

                    //create newFriend user object from what is double clicked
                    User newFriend = (User) list.getSelectedValue();
                    //add newFriend to myFriends arraylist
                    myFriends.add(newFriend);

                    //this line is for testing. I know its adding to array when the size goes up.
                    System.out.print(myFriends.size());


                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        lblAllUsersTitle = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listSearchResults = new javax.swing.JList();
        txtSearch = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listAllUsers = new javax.swing.JList();

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                clearArrayList(evt);
            }
        });

        lblAllUsersTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblAllUsersTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblAllUsersTitle.setText("All Users");

        jScrollPane2.setViewportView(listSearchResults);

        txtSearch.setText("Type Friend's name here.");
        txtSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSearchActionPerformed(evt);
            }
        });

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                    .addComponent(txtSearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
        );

        jScrollPane1.setViewportView(listAllUsers);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblAllUsersTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lblAllUsersTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSearchActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSearchActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        try {
            // locate contacts on server and return an ArrayList named searchContacts
            registry = LocateRegistry.getRegistry();
            IContacts contacts = (IContacts) registry.lookup("AllContacts");
            ArrayList<User> searchContacts = contacts.getUserList();

            // creates an ArrayList to hold searchResults
            ArrayList<User> searchResults = new ArrayList<User>();

            // create user based on text box to be used to search against all users
            String strSearchUsers = txtSearch.getText();
            User searchUser = new User();
            searchUser.setUserName(strSearchUsers);


            //if search on contacts ArrayList contains user input add the user object to the search results ArrayList 
            if (searchContacts.contains(searchUser) == true) {
                searchResults.add(searchUser);

            } else {
                // display error if no matching user is found
                JOptionPane.showMessageDialog(null, strSearchUsers + " not found. Please try another name.");
            }

            // add user to results model
            for (int i = 0; i < searchResults.size(); i++) {
                //work around for getting proper string to display
                User dispUser = new DisplayableUser();
                dispUser.setUserName(searchUser.getUserName());
                //add user to default list model
                resultsModel.add(i, dispUser);
            }

            // add searchResults model to JList
            listSearchResults.setModel(resultsModel);


        } catch (RemoteException ex) {
            Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NotBoundException ex) {
            Logger.getLogger(AddFriendsUI.class.getName()).log(Level.SEVERE, null, ex);

        }
    }//GEN-LAST:event_btnSearchActionPerformed

    //this method is run in place of default window is closing event
    private void clearArrayList(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_clearArrayList
        //clear the all contacts array list here so the UI will create a fresh one every time
        allContacts = null;
        //clear default list model on closing
        allModel.clear();
        //dispose of UI
        this.dispose();
    }//GEN-LAST:event_clearArrayList

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws RemoteException, NotBoundException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AllUsersUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AllUsersUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AllUsersUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AllUsersUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new AllUsersUI().setVisible(true);
                } catch (RemoteException ex) {
                    Logger.getLogger(AllUsersUI.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NotBoundException ex) {
                    Logger.getLogger(AllUsersUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });



    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSearch;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblAllUsersTitle;
    private javax.swing.JList listAllUsers;
    private javax.swing.JList listSearchResults;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
}
